package org.iks.user.web.service.impl;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.iks.common.ResultCode;
import org.iks.common.exception.BusinessException;
import org.iks.common.util.HashUtil;
import org.iks.user.web.entity.UserEntity;
import org.iks.user.web.mapper.UserMapper;
import org.iks.user.web.service.UserService;
import org.iks.user.web.vo.UserInfoVo;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author kzou
 * @date 2023/12/30 11:11
 * @description:
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, UserEntity> implements UserService {

    @Override
    public UserEntity userLogin(String publicKey) {
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getPublicAddress, publicKey);
        UserEntity result = baseMapper.selectOne(wrapper);
        if (result == null) {
            // register
            result = userRegister(publicKey);
        }
        return result;
    }

    public UserEntity userRegister(String publicKey) {
        UserEntity userEntity = queryUserByAccount(publicKey);
        if (userEntity != null) {
            throw new BusinessException(ResultCode.USER_ACCOUNT_HAS_EXIST);
        }
        UserEntity result = new UserEntity();
        long account = HashUtil.hash(publicKey);
        account = Math.abs(account);
        result.setAccount(account + "");
        result.setPublicAddress(publicKey);
        // hash 冲突 多次hash
        if (queryUserByAccount(account + "") != null) {
            log.info("user account hash reflect: {}=>{}", publicKey, account);
            account = HashUtil.hash(publicKey + RandomUtil.randomString(6));
            result.setAccount(account + "");
        }
        // 默认值
        result.setAvatar("https://tse1-mm.cn.bing.net/th/id/OIP-C.qebt1PBL2zYXGXsHVMPTXAAAAA");
        int length = result.getAccount().length();
        result.setUsername("用户" + result.getAccount().substring(length - 4, length));
        baseMapper.insert(result);
        return result;
    }

    @Override
    public UserEntity queryUserByAccount(String account) {
        LambdaQueryWrapper<UserEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserEntity::getAccount, account);
        return baseMapper.selectOne(wrapper);
    }

    @Override
    public List<UserInfoVo> simpleSearch(String account) {
        List<UserInfoVo> userInfoVos = baseMapper.searchUserByName(account);
        return userInfoVos;
    }

    public String encodePassword(String originalPassword) {
        return SecureUtil.sha256(originalPassword);
    }


}
